﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.ExportToRTR.CUiExportToRTROutputViewModel
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnExternalMotionPlanners.CommunicationWrapper.RTR;
using DnExternalMotionPlanners.CommunicationWrapper.Services;
using EngineeringInternalExtension;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using System.Windows.Threading;
using Tecnomatix.Engineering;

namespace DnProcessSimulateCommands.ExportToRTR
{
    public class CUiExportToRTROutputViewModel : CUiExportToRTRObservable
    {
        private List<string> _existingProjectInHost;
        private Action _refreshStatus;
        private bool _installProject;
        private string _machineName;
        private string _packageName;
        private bool _isValidProject;
        private string _packageNameToolTip = string.Empty;
        private Visibility _packageNameToolTipVisibility;
        private bool _packageNameTootTipShow = true;
        private ToolTip _machineNameToolTip;
        private readonly string INSTALL_PROJECT_KEY = nameof(InstallProject);
        private readonly string DENSE_CONNECTION_KEY = nameof(DenseConnection);
        private readonly string AUTO_CONNECT_ALL_KEY = nameof(AutoConnectAll);
        private readonly string IP_KEY = "IP";

        public string ExportPath { get; set; } = string.Empty;

        public bool DenseConnection { get; set; } = true;

        public bool AutoConnectAll { get; set; } = true;

        private bool InInitialization { get; set; }

        private CApExportToRTRStatusManager StatusManager { set; get; }

        public bool InstallProject
        {
            get => this._installProject;
            set
            {
                this.Set<bool>(ref this._installProject, value, nameof(InstallProject));
                if (!this._installProject)
                    return;
                this.UpdateProjectName();
                Action refreshStatus = this._refreshStatus;
                if (refreshStatus == null)
                    return;
                refreshStatus();
            }
        }

        public string MachineName
        {
            get => this._machineName;
            set
            {
                if (!(this._machineName != value))
                    return;
                this.Set<string>(ref this._machineName, value, nameof(MachineName));
                if (this.InInitialization || !this.InstallProject)
                    return;
                CApExportToRTRStatusManager.IssueType issue;
                this.InitializeMachine(out issue);
                this.UpdateStatusForInitializeMachine(issue);
                this.UpdateProjectName();
                Action refreshStatus = this._refreshStatus;
                if (refreshStatus == null)
                    return;
                refreshStatus();
            }
        }

        public string PackageName
        {
            get => this._packageName;
            set
            {
                this.Set<string>(ref this._packageName, value, nameof(PackageName));
                this.UpdateProjectName();
                Action refreshStatus = this._refreshStatus;
                if (refreshStatus == null)
                    return;
                refreshStatus();
            }
        }

        public string FullExportPath
        {
            get
            {
                if (string.IsNullOrEmpty(this.ExportPath))
                    this.ExportPath = TxApplicationEx.CreateSessionTemporaryFolder("_rtr");
                return Path.Combine(this.ExportPath, this.PackageName);
            }
        }

        public bool IsValidProject
        {
            get => this._isValidProject;
            set => this.Set<bool>(ref this._isValidProject, value, nameof(IsValidProject));
        }

        public string PackageNameToolTip
        {
            get => this._packageNameToolTip;
            set => this.Set<string>(ref this._packageNameToolTip, value, nameof(PackageNameToolTip));
        }

        private Visibility PackageNameToolTipVisibility
        {
            get => this._packageNameToolTipVisibility;
            set
            {
                this.Set<Visibility>(ref this._packageNameToolTipVisibility, value, nameof(PackageNameToolTipVisibility));
            }
        }

        public bool PackageNameTootTipShow
        {
            get => this._packageNameTootTipShow;
            set
            {
                this.Set<bool>(ref this._packageNameTootTipShow, value, nameof(PackageNameTootTipShow));
            }
        }

        public ToolTip MachineNameToolTip
        {
            get => this._machineNameToolTip;
            set => this.Set<ToolTip>(ref this._machineNameToolTip, value, nameof(MachineNameToolTip));
        }

        internal CUiExportToRTROutputViewModel(
          CApExportToRTRStatusManager statusManager,
          Action refreshStatus)
        {
            this.StatusManager = statusManager;
            this._refreshStatus = refreshStatus;
            this.LoadData();
        }

        public void PersistConnectionSettings()
        {
            CApExportToRTRUtils.SaveValueToRegistry(this.DENSE_CONNECTION_KEY, this.DenseConnection.ToString());
            CApExportToRTRUtils.SaveValueToRegistry(this.AUTO_CONNECT_ALL_KEY, this.AutoConnectAll.ToString());
            if (string.IsNullOrEmpty(this.MachineName))
                return;
            CApExportToRTRUtils.SaveValueToRegistry(this.IP_KEY, this.MachineName.ToString());
        }

        private void LoadData()
        {
            this.LoadProjectName();
            this.LoadInstallProject();
            this.LoadConnectionSettings();
        }

        private void LoadProjectName()
        {
            this.PackageName = TxApplication.ActiveDocument.CurrentStudy.Name;
        }

        private void LoadInstallProject()
        {
            string str = CApExportToRTRUtils.ReadValueFromRegistry(this.INSTALL_PROJECT_KEY);
            if (!string.IsNullOrEmpty(str) && str.Equals("False"))
                this.InstallProject = false;
            else
                this.InstallProject = true;
        }

        private void LoadConnectionSettings()
        {
            string str1 = CApExportToRTRUtils.ReadValueFromRegistry(this.DENSE_CONNECTION_KEY);
            if (!string.IsNullOrEmpty(str1) && str1.Equals("False"))
                this.DenseConnection = false;
            string str2 = CApExportToRTRUtils.ReadValueFromRegistry(this.AUTO_CONNECT_ALL_KEY);
            if (!string.IsNullOrEmpty(str2) && str2.Equals("False"))
                this.AutoConnectAll = false;
            string str3 = CApExportToRTRUtils.ReadValueFromRegistry(this.IP_KEY);
            if (string.IsNullOrEmpty(str3))
                return;
            this._machineName = str3;
        }

        internal void Initialize()
        {
            if (!this.InstallProject)
                return;
            Dispatcher.CurrentDispatcher.BeginInvoke((Action)(() =>
            {
                this.InInitialization = true;
                TxApplication.LogWriter.WriteInfoLine("RTR Export - Getting the IP of the WSL");
                string machineConnectionIp = ConnectionUtils.CurrentMachineConnectionIp;
                TxApplication.LogWriter.WriteInfoLine("RTR Export - The wsl machine IP is: " + machineConnectionIp);
                bool flag = false;
                CApExportToRTRStatusManager.IssueType issue = CApExportToRTRStatusManager.IssueType.NoIssue;
                if (!string.IsNullOrEmpty(machineConnectionIp))
                {
                    string machineName = this.MachineName;
                    this.MachineName = machineConnectionIp;
                    if (this.InitializeMachine(out issue))
                        flag = true;
                    else
                        this.MachineName = machineName;
                }
                if (!flag && this.InitializeMachine(out issue))
                    ;
                this.UpdateStatusForInitializeMachine(issue);
                this.UpdateProjectName();
                this.UpdateCollisionSets();
                Action refreshStatus = this._refreshStatus;
                if (refreshStatus != null)
                    refreshStatus();
                this.InInitialization = false;
            }), DispatcherPriority.Background);
        }

        private void UpdateCollisionSets()
        {
            if (!TxApplication.ActiveDocument.CollisionRoot.PairList.ToList<ITxObject>().TrueForAll((Predicate<ITxObject>)(x => !(x as TxCollisionPair).Active)))
                return;
            this.StatusManager.AddIssue(CApExportToRTRStatusManager.IssueType.NoActiveCollisionSets);
        }

        private bool InitializeMachine(out CApExportToRTRStatusManager.IssueType issue)
        {
            bool flag = true;
            issue = CApExportToRTRStatusManager.IssueType.NoIssue;
            if (string.IsNullOrEmpty(this.MachineName))
            {
                issue = CApExportToRTRStatusManager.IssueType.NoIP;
                this._existingProjectInHost = (List<string>)null;
                this.IsValidProject = false;
            }
            else
            {
                string message;
                if (!this.IsMachineAlive(this.MachineName, out message))
                {
                    issue = CApExportToRTRStatusManager.IssueType.CouldNotAccessMachine;
                    this._existingProjectInHost = (List<string>)null;
                    this.IsValidProject = false;
                    flag = false;
                    TxApplication.LogWriter.WriteInfoLine("RTR Export - Machine live check: " + this.MachineName + " error - " + message);
                }
                else
                {
                    TxApplication.LogWriter.WriteInfoLine("RTR Export - Machine live check: " + this.MachineName + " is valid ");
                    DnExMopRTRRestApiInterface restApi = new DnExMopRTRRestApiInterface(this.MachineName);
                    List<string> projects = (List<string>)null;
                    bool success = false;
                    Task.Run<(bool, List<string>)>((Func<Task<(bool, List<string>)>>)(async () =>
                    {
                        (bool, List<string>) valueTuple = await restApi.RequestListOfInstalledProjects();
                        success = valueTuple.Item1;
                        projects = valueTuple.Item2;
                        return (valueTuple.Item1, valueTuple.Item2);
                    })).Wait();
                    if (success)
                    {
                        this._existingProjectInHost = projects;
                        TxApplication.LogWriter.WriteInfoLine("RTR Export - Machine live check project list found");
                    }
                    else
                    {
                        issue = CApExportToRTRStatusManager.IssueType.RestApiAccess;
                        this._existingProjectInHost = (List<string>)null;
                        TxApplication.LogWriter.WriteInfoLine("RTR Export - Machine live check error - no project list is found");
                    }
                    List<string> existingProjectInHost = this._existingProjectInHost;
                    // ISSUE: explicit non-virtual call
                    if ((existingProjectInHost != null ? (__nonvirtual(existingProjectInHost.Count) >= 10 ? 1 : 0) : 0) != 0)
                        issue = CApExportToRTRStatusManager.IssueType.NoAvailableProjectSlots;
                }
            }
            return flag;
        }

        private void UpdateStatusForInitializeMachine(CApExportToRTRStatusManager.IssueType issue)
        {
            if (issue != CApExportToRTRStatusManager.IssueType.RestApiAccess)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.RestApiAccess);
            if (issue != CApExportToRTRStatusManager.IssueType.NoIP)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.NoIP);
            if (issue != CApExportToRTRStatusManager.IssueType.CouldNotAccessMachine)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.CouldNotAccessMachine);
            if (issue != CApExportToRTRStatusManager.IssueType.NoAvailableProjectSlots)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.NoAvailableProjectSlots);
            if (issue == CApExportToRTRStatusManager.IssueType.NoIssue)
                return;
            this.StatusManager.AddIssue(issue);
        }

        private bool UpdateProjectName()
        {
            bool flag1 = true;
            CApExportToRTRStatusManager.IssueType issue = CApExportToRTRStatusManager.IssueType.NoIssue;
            if (this.InstallProject)
            {
                if (string.IsNullOrEmpty(this._packageName))
                    issue = CApExportToRTRStatusManager.IssueType.NoPackageName;
                else if (this.IsInvalidValidPath(this._packageName))
                    issue = CApExportToRTRStatusManager.IssueType.PackageNameCharacters;
                else if (this._existingProjectInHost != null)
                {
                    bool flag2 = false;
                    foreach (string str in this._existingProjectInHost)
                    {
                        if (str == this._packageName)
                        {
                            flag2 = true;
                            flag1 = false;
                            break;
                        }
                    }
                    if (flag2)
                        issue = CApExportToRTRStatusManager.IssueType.PackageNameExist;
                }
                else
                    flag1 = false;
            }
            this.IsValidProject = issue != CApExportToRTRStatusManager.IssueType.NoIssue;
            this.UpdatePackageNameIssue(issue);
            return flag1;
        }

        private void UpdatePackageNameIssue(CApExportToRTRStatusManager.IssueType issue)
        {
            if (issue != CApExportToRTRStatusManager.IssueType.NoPackageName)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.NoPackageName, "PackageName");
            if (issue != CApExportToRTRStatusManager.IssueType.PackageNameCharacters)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.PackageNameCharacters, "PackageName");
            if (issue != CApExportToRTRStatusManager.IssueType.PackageNameExist)
                this.StatusManager.RemoveIssue(CApExportToRTRStatusManager.IssueType.PackageNameExist, "PackageName");
            if (issue == CApExportToRTRStatusManager.IssueType.NoIssue)
                return;
            this.StatusManager.AddIssueWithScope(issue, "PackageName", "PackageName");
        }

        private bool IsInvalidValidPath(string path)
        {
            return this._packageName.IndexOfAny(Path.GetInvalidPathChars()) != -1 || this._packageName.IndexOfAny(Path.GetInvalidFileNameChars()) != -1;
        }

        private bool IsMachineAlive(string machineName, out string message)
        {
            bool flag = false;
            if (ConnectionUtils.IsMachineAlive(machineName, out message))
                flag = true;
            return flag;
        }
    }
}
